
package com.platform.modules.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.common.annotation.SysLog;
import com.platform.common.utils.Constant;
import com.platform.common.utils.RestResponse;
import com.platform.common.utils.StringUtils;
import com.platform.modules.bk.entity.BkCustomerEntity;
import com.platform.modules.bk.service.BkCustomerService;
import com.platform.modules.mall.entity.MallUserEntity;
import com.platform.modules.mall.service.MallUserIntegralLogService;
import com.platform.modules.mall.service.MallUserService;
import com.platform.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 会员Controller
 *
 * @author
 * @date 2019-07-01 14:59:40
 */
@RestController
@RequestMapping("mall/user")
public class MallUserController extends AbstractController {
    @Autowired
    private MallUserService mallUserService;
    @Autowired
    private MallUserIntegralLogService userIntegralLogService;
    @Autowired
    private BkCustomerService bkCustomerService;

    /**
     * 查看所有列表
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @RequestMapping("/queryAll")
    public RestResponse queryAll(@RequestParam Map<String, Object> params) {
        List<MallUserEntity> list = mallUserService.queryAll(params);
        return RestResponse.success().put("list", list);
    }

    /**
     * 查看所有列表
     *
     * @return RestResponse
     */
    @RequestMapping("/queryUserIdName")
    public RestResponse queryUserIdName() {
        List<MallUserEntity> list = mallUserService.list(new QueryWrapper<MallUserEntity>().select("ID,USER_NAME"));
        return RestResponse.success().put("list", list);
    }

    /**
     * 分页查询会员
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @GetMapping("/list")
    @RequiresPermissions("mall:user:list")
    public RestResponse list(@RequestParam Map<String, Object> params) {
        Page page = mallUserService.queryPage(params);
        return RestResponse.success().put("page", page);
    }

    /**
     * 根据主键查询会员详情
     *
     * @param id 主键
     * @return RestResponse
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("mall:user:info")
    public RestResponse info(@PathVariable("id") String id) {
        MallUserEntity mallUser = mallUserService.getById(id);

        return RestResponse.success().put("user", mallUser);
    }

    /**
     * 新增会员
     *
     * @param mallUser mallUser
     * @return RestResponse
     */
    @SysLog("新增会员")
    @RequestMapping("/save")
    @RequiresPermissions("mall:user:save")
    public RestResponse save(@RequestBody MallUserEntity mallUser) {
        mallUserService.add(mallUser);
        return RestResponse.success();
    }

    /**
     * 修改会员
     *
     * @param mallUser mallUser
     * @return RestResponse
     */
    @SysLog("修改会员")
    @RequestMapping("/update")
    @RequiresPermissions("mall:user:update")
    public RestResponse update(@RequestBody MallUserEntity mallUser) {
        mallUserService.update(mallUser);
        return RestResponse.success();
    }

    /**
     * 修改会员
     *
     * @param mallUser mallUser
     * @return RestResponse
     */
    @SysLog("修改会员")
    @RequestMapping("/updateUserMobile")
    @RequiresPermissions("mall:user:update")
    public RestResponse updateUserMobile(@RequestBody MallUserEntity mallUser) {
        if (mallUser == null || StringUtils.isBlank(mallUser.getMobile()) || StringUtils.isBlank(mallUser.getId())) {
            return RestResponse.error("缺少参数");
        }
        mallUserService.update(new LambdaUpdateWrapper<MallUserEntity>()
                .set(MallUserEntity::getMobile, mallUser.getMobile())
                .eq(MallUserEntity::getId, mallUser.getId()));

        return RestResponse.success();
    }

    /**
     * 修改会员积分
     *
     * @param mallUser mallUser
     * @return RestResponse
     */
    @SysLog("修改会员积分")
    @RequestMapping("/updateByIntegral")
    @RequiresPermissions("mall:user:update")
    public RestResponse updateByIntegral(@RequestBody MallUserEntity mallUser) {
        MallUserEntity oldUser = mallUserService.getById(mallUser.getId());
        boolean flag = mallUser.getSignAllIntegral().compareTo(BigDecimal.ZERO) > 0;
        BigDecimal allIntegral = oldUser.getSignAllIntegral();
        if (StringUtils.isNotBlank(oldUser.getCustomerNo())) {
            BkCustomerEntity customerEntity = bkCustomerService.getById(oldUser.getCustomerNo());
            if (customerEntity != null) {
                allIntegral = oldUser.getSignAllIntegral().add(customerEntity.getAvailablePoints());
            }
        }
        // todo 用户表和关联表的积分修改
        userIntegralLogService.add(mallUser.getId(), mallUser.getSignAllIntegral().abs(), allIntegral,
                flag ? Constant.IntegralType.INCOME : Constant.IntegralType.PAYOUT
                , "后台修改");

        // 负值需要减去
        if (!flag) {
            BigDecimal actualPrice = mallUser.getSignAllIntegral().abs(), signAllIntegral = oldUser.getSignAllIntegral();
            boolean greater = actualPrice.compareTo(signAllIntegral) > 0,
                    equal = actualPrice.compareTo(signAllIntegral) == 0,
                    less = actualPrice.compareTo(signAllIntegral) < 0;
            flag = mallUserService.update(new LambdaUpdateWrapper<MallUserEntity>()
                    .set(greater || equal, MallUserEntity::getSignAllIntegral, 0)
                    .set(less, MallUserEntity::getSignAllIntegral, signAllIntegral.subtract(actualPrice))
                    .eq(MallUserEntity::getId, oldUser.getId())
            );
            // 积分大于用户活动获取的积分则抵扣后在减去存款积分，其他直接抵扣用户活动获取的积分
            if (greater && StringUtils.isNotBlank(oldUser.getCustomerNo())) {
                bkCustomerService.updatePoints(actualPrice.subtract(oldUser.getSignAllIntegral()),
                        Constant.IntegralType.PAYOUT.getValue(), oldUser.getCustomerNo());
            }
        } else {
            flag = mallUserService.update(new LambdaUpdateWrapper<MallUserEntity>()
                    .set(MallUserEntity::getSignAllIntegral, oldUser.getSignAllIntegral().add(mallUser.getSignAllIntegral()))
                    .eq(MallUserEntity::getId, oldUser.getId()));
        }
        return RestResponse.success();
    }

    /**
     * 根据主键删除会员
     *
     * @param ids ids
     * @return RestResponse
     */
    @SysLog("删除会员")
    @RequestMapping("/delete")
    @RequiresPermissions("mall:user:delete")
    public RestResponse delete(@RequestBody String[] ids) {
        mallUserService.deleteBatch(ids);

        return RestResponse.success();
    }
}
